<template>
  <view class="tab-bar">
    <view v-for="(item, index) in userTabbar" :class="'tab-bar-item item-' + index" @click="jump(item)">
      <image class="icon" :src="current == item.index ? item.selectedIconPath : item.iconPath"></image>
      <view class="text" :class="current == item.index ? 'active' : ''"> {{ item.text }}</view>
    </view>
  </view>
</template>

<script setup>
  import { ref, getCurrentInstance } from 'vue';

  const props = defineProps({
    current: Number,
  });
  const emit = defineEmits(['barHeight']);

  // 获取当前组件实例
  const instance = getCurrentInstance();

  const barHeight = ref(0);

  const userTabbar = ref([
    {
      iconPath: '/static/icon/home.png', // 未点击的图标
      selectedIconPath: '/static/icon/home_active.png', // 已点击的图标
      text: '首页', // 标题
      pagePath: '/pages/index/index', // 页面路径
      name: '首页', // 名字
      index: '0', // 下标
    },
    {
      iconPath: '/static/icon/message.png', // 未点击的图标
      selectedIconPath: '/static/icon/message_active.png', // 已点击的图标
      text: '消息',
      pagePath: '/pages/message/message',
      name: '消息',
      index: '1',
    },
    {
      iconPath: '/static/icon/my.png', // 未点击的图标
      selectedIconPath: '/static/icon/my_active.png', // 已点击的图标
      text: '我的',
      pagePath: '/pages/my/my',
      name: '消息',
      index: '2',
    },
  ]);

  console.log('userTabbar >>>>>', userTabbar);

  // 计算 tabbar 渲染高度
  let query = uni.createSelectorQuery().in(instance);
  query
    .select('.tab-bar')
    .boundingClientRect((rect) => {
      emit('barHeight', rect.height);
    })
    .exec();

  // 点击跳转对应tabbar页面
  function jump(item) {
    uni.switchTab({
      url: item.pagePath,
    });
  }

  function getHeight() {
    return barHeight.value;
  }

  // 暴露方法
  defineExpose({
    getHeight,
  });
</script>

<style lang="scss" scoped>
  .tab-bar {
    display: flex;
    justify-content: space-around;
    align-items: center;
    position: fixed;
    width: 100%;
    min-height: 110rpx;
    bottom: 0;
    padding-top: calc(env(safe-area-inset-bottom) / 2 - 20rpx);
    padding-bottom: calc(env(safe-area-inset-bottom) / 2 + 10rpx);
    background-color: #fff;
    box-shadow: rgba(0, 0, 0, 0.12) 0px 1px 3px, rgba(0, 0, 0, 0.24) 0px 1px 2px;
  }

  .tab-bar-item {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }

  .tab-bar-item .icon {
    width: 40rpx;
    height: 40rpx;
    margin-bottom: 10rpx;
  }

  .tab-bar-item .text {
    font-weight: 600;
    font-size: 24rpx;
    color: #000000;

    &.active {
      color: #3b6cfa;
    }
  }
</style>
